/*
 * @Author       : wfl
 * @LastEditors: ww
 * @description  :
 * @updateInfo   :
 * @Date         : 2022-11-07 16:08:42
 * @LastEditTime: 2023-06-28 14:54:16
 */
import { defineComponent, ref, withModifiers } from 'vue'
import { _ } from 'iking-utils'
import type { Ref } from 'vue'
import IkPageFull from '@g/components/LayoutCom/IkPageFull/index.vue'
import IkSplitPan from '@g/components/LayoutCom/IkSplitPan/index.vue'
import IkItemList from '@g/components/BaseCom/IkItemList/index.vue'
import RoleModal from './RoleEditModal.vue'
import RoleListComfig from './RoleListConfig'
import IkSvgIcon from '@/global/components/BaseCom/IkSvgIcon/index.vue'
import { roleApi } from '@/MainApp/apis/role'
import type { RoleFormState } from '@/global/enums/role'

const roleManage = defineComponent({
  components: {
    RoleListComfig,
    RoleModal
  },
  setup() {
    const { msgWarning, msgSuccess, msgBoxWarnAsync } = useMessage()

    const loading = ref(false)

    const visible = ref(false)
    const editData: Ref<RoleFormState | null> = ref(null)
    const refRole = ref()
    const helpState = ref(false)
    const selectId: Ref<RoleFormState | null> = ref(null)

    const roleLists: Ref<
      Array<
        RoleFormState & {
          label?: string
          value?: any
        }
      >
    > = ref([])
    const __roleLists: Ref<Array<RoleFormState>> = ref([])
    // let recordList: Array<RoleFormState> = []
    // 过滤
    // const searchText = ref('')
    const selectIdName = ref('')
    watch(
      () => visible.value,
      vis => {
        !vis && (editData.value = null)
      }
    )
    watch(
      () => selectId.value,
      vis => {
        if (vis)
          selectIdName.value = vis.name || ''
      }
    )
    // const filterRole = () => {
    //   roleLists.value.filter(role => role.name === searchText.value)
    // }

    // 获取权限
    const getRoleList = async () => {
      loading.value = true
      const { success, data, msg } = await roleApi.getRoleList()
      if (success) {
        const LIST = data.sort((a: any, b: any) => a.sortOrder! - b.sortOrder!)
        roleLists.value = _.cloneDeep(LIST)
        // recordList = _.cloneDeep(LIST)
        __roleLists.value = _.cloneDeep(LIST)
        selectId.value = data.length > 0 ? data?.[0] : null
      }
      else {
        msgWarning(msg)
      }
      loading.value = false
    }

    // 新增角色
    const handAddNewRole = () => {
      visible.value = true
    }
    // 切换选中角色
    const handSelectRole = (role: RoleFormState) => {
      checkChange.value = false
      selectId.value = role
    }
    // 编辑角色
    const handEditRole = (role: RoleFormState) => {
      visible.value = true
      editData.value = role
    }
    // 删除角色
    const handDeleteRole = async (role: RoleFormState) => {
      msgBoxWarnAsync(
        '删除角色',
        `删除后，角色【${role.name}】相关的用户将不能继续使用本角色菜单，无法恢复。确定删除吗？`,
        async () => {
          const { success, msg } = await roleApi.deleteRole(role.id)
          if (success) {
            msgSuccess(msg)
            getRoleList()
          }
          else {
            msgWarning(msg)
          }
        }
      )
    }

    const checkChange = ref(false)
    // 选项变化
    const handCheckChange = (bool: boolean) => {
      checkChange.value = bool
    }

    onMounted(() => {
      getRoleList()
    })
    // const searchRole = () => {
    //   if (searchText.value) {
    //     roleLists.value = roleLists.value.filter(
    //       item => item.name?.indexOf(searchText.value) !== -1
    //     )
    //   }
    //   else {
    //     roleLists.value = recordList
    //   }
    // }
    return () => (
      <>
        <IkSplitPan size={0} left-size={[0, 100]}>
          {{
            left: (
              <>
                <IkPageFull
                  header-title="角色列表"
                  refreshBtn={false}
                  settingBtn={false}
                  headerBorder={true}
                >
                  {{
                    headerRight: (
                      <>
                        <IkSvgIcon
                          show-bg
                          width={40}
                          pop
                          size="big"
                          title='刷新'
                          name="icon-shuaxin1"
                          onClick={() => getRoleList()}
                        />
                        <IkSvgIcon
                          v-role="ADD-ROLE"
                          onClick={() => handAddNewRole()}
                          show-bg
                          title='新增'
                          pop
                          size="big"
                          width={40}
                          font-size={40}
                          name="icon-xinzeng"
                        />
                      </>
                    ),
                    table: (
                      <>
                        <IkItemList
                            list={roleLists.value as any}
                            onSelect={(role: any) => handSelectRole(role)}
                            proxy={{ label: 'name', value: 'id' }}
                            confirmLeave={checkChange.value}
                            confirmLeaveText="当前角色配置未保存，是否确定切换？"
                          >
                            {{
                              suffix: ({ item }: { item: any; }) => (
                                <span class="flex">
                                  <IkSvgIcon title="编辑" pop show-bg width={28} v-role="UPDATE-ROLE" name="iksvg_bianji" onClick={withModifiers(
                                    () => handEditRole(item),
                                    ['stop']
                                  )} />
                                  <IkSvgIcon title="删除" pop show-bg width={28} type="warning" v-role="DELETE-ROLE" name="iksvg_shanchu" onClick={withModifiers(
                                    () => handDeleteRole(item),
                                    ['stop']
                                  )} />
                                </span>
                              )
                            }}
                          </IkItemList>
                      </>
                    )
                  }}
                </IkPageFull>
              </>
            ),
            right: (
              <>
                  <IkPageFull
                    refreshBtn={false}
                    settingBtn={false}
                    header-title={
                      selectId.value?.name
                        ? `${selectId.value?.name} [数据权限：${selectId.value?.dataScopeTypeName}]`
                        : ''
                    }
                  >
                    {{
                      headerRight: (
                        <IkSvgIcon
                          v-show={selectId.value?.name}
                          v-role="UPDATE-ROLE-MENU"
                          onClick={() => (helpState.value = !helpState.value)}
                          show-bg
                          pop
                          size="big"
                          title='保存配置'
                          name="iksvg_guidang"
                        />
                      ),
                      table: <RoleListComfig
                          onCheckChange={bool => handCheckChange(bool) }
                          role={selectId.value!}
                          ref={refRole as any}
                          helpState={helpState.value}
                          check={checkChange.value}
                        />

                    }}
                  </IkPageFull>
              </>
            )
          }}
        </IkSplitPan>
        <RoleModal
          v-model:visible={visible.value}
          editData={editData.value}
          onDataChange={() => getRoleList()}
        />
      </>
    )
  }
})

export default roleManage
